package com.module.chat;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Collections;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;

import org.phprpc.util.PHPSerializer;
import org.xsocket.connection.INonBlockingConnection;

import com.connect.agreement.Packet;
import com.game.manager.SobManager;
import com.game.performers.Actor;
import com.server.User;

public class ChatManager {
	public static final int ChannelLogin = 1;
	
	//当前
	public static final int ChannelCurrent = 10;
	//区域
	public static final int ChannelZone = 11;
	//世界
	public static final int ChannelWorld = 12;
	//组队
	public static final int ChannelTeam = 13;
	public static final int ChannelUnion = 14;
	public static final int ChannelPrivate = 17;
	
	private static final Set<INonBlockingConnection> sessions = Collections.synchronizedSet(new HashSet<INonBlockingConnection>());
	
	private static final Hashtable<String, INonBlockingConnection> connections = new Hashtable<String, INonBlockingConnection>();
	
	public static void addConnect(INonBlockingConnection nbc){
		synchronized (sessions) {
			sessions.add(nbc);
			connections.put(nbc.getId(), nbc);
		}
	}
	
	public static void removeConnect(INonBlockingConnection nbc){
		synchronized (sessions) {
			sessions.remove(nbc);
			connections.remove(nbc.getId());
		}
	}
	
	public static void sendMessageToAll(ChatPacket packet) {
        try {
            synchronized (sessions) {
                Iterator<INonBlockingConnection> iter = sessions.iterator();
                while (iter.hasNext()) {
                    INonBlockingConnection nbConn = (INonBlockingConnection) iter.next();
                    if (nbConn.isOpen()) {
                    	nbConn.write((packet.byteBuffer()));
                    	nbConn.flush();
                    }
                }
            }
        } catch (Exception ex) {
            System.out.println("sendMessageToAll: " + ex.getMessage());
        }
    }
  
	public static void update(INonBlockingConnection nbc, ChatPacket packet){
		if(packet == null){
			return;
		}
		ChatMessage msg = null;
		try {
			msg = (ChatMessage) new PHPSerializer().unserialize(packet.getContent());
			switch(packet.getChannel()){
			case ChannelLogin://登录
				Actor actor = (Actor)SobManager.get().getSob(msg.fromrid);
				User user = User.getUserByMirror(actor.pid);
				if(user.ctrl == msg.fromrid){
					nbc.write(packet.byteBuffer());
				}
				break;
			case ChannelCurrent:
				
				break;
			case ChannelZone:
						
				break;
			case ChannelWorld:
				
				break;
			case ChannelTeam:
				
				break;
			case ChannelUnion:
				
				break;
			case ChannelPrivate:
				
				break;
			}
		} catch (Exception e) {
			System.out.println("收到的聊天包发生错误");
			e.printStackTrace();
			return;
		}
	}
}
